import types
from validator import ValidatorResults
from __init__ import Microformat, MicroformatProperty, MicroformatPropertyGenerator, MicroformatNotFoundError, register_property
from parser import BaseMicroformatProcessor

class HCardParser(BaseMicroformatProcessor):
    def node_is_microformat(self, attrs):
        for attr in attrs:
            if attr[0] == 'class' and attr[1].find("vcard") >= 0:
                return True
        return False


class HCard(Microformat):
    """
    The HCard microformat class
    
    """
    
    name = "hcard"
    schema = {
        'required': [
            MicroformatPropertyGenerator('hcard', 'fn'),
            MicroformatPropertyGenerator('hcard', 'n')
        ],
        'optional': [
            'n','email','adr','geo','org','tel', 'family-name', 'given-name', 'additional-name', 'honorific-prefix',
            'honorific-suffix', 'nickname','sort-string',
            ['url', {'a': 'href', 'area': 'href', 'img': 'src'}],
            'type','tel','post-office-box',
            'extended-address', 'street-address', 'locality', 'region', 'postal-code',
            'country-name', 'label', 'latitude', 'longitude', 'tz', 'photo', 'logo',
            'sound', 'bday','title', 'role','organization-name',
            'organization-unit','category', 'note','class', 'key', 'mailer', 'uid',
            'rev'
        ]
    }
    
    @register_property()
    def fn(name):
        class HCardFNameProperty(MicroformatProperty):
            def is_required(self, mf):
                if mf.get_property('n').value == None: return True
                return False
        return HCardFNameProperty(name)
    
    @register_property()
    def n(name):
        class HCardNameProperty(MicroformatProperty):
            def is_required(self, mf):
                if mf.get_property('fn').value == None: return True
                return False
        return HCardNameProperty(name)
    
    def parse(self, data):
        """Create the HCardParser and start the parsing process"""
        self.parser = HCardParser(self)
        Microformat.parse(self, data)
    
    def validate(self):
        results = ValidatorResults()
        if self.count > 0:
            for requirement in HCard.schema['required']:
                if isinstance(requirement, MicroformatPropertyGenerator):
                    requirement = requirement.name
                if self.get_property(requirement).value == None and self.get_property(requirement).is_required(self):
                    results.add(requirement, '%s is required' % requirement)
        return results
